{extend name="admin@index_layout"/}
{block name="main"}
<div class="layui-card">
    <style>
        #selectedProducts p {
            color: #0C0C0C;
        }

        .layui-form-label {
            width: 120px !important;
        }
    </style>
    <div class="layui-card-body">
        <div class="layui-tab layui-tab-card">
            <div class="layui-tab-content">
                <form class="layui-form data-form" method="post" id="selfForm">
                    <div class="layui-form-item">
                        <label class="layui-form-label">选择商品:</label>
                        <div class="layui-input-block">
                            <button type="button" class="layui-btn" id="addProductBtn">+ 添加</button>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">已选商品列表:</label>
                        <div class="layui-input-block">
                            <table class="layui-table" style="width: 60vw;">
                                <colgroup>
                                    <col width="120">
                                    <col>
                                    <col width="150">
                                    <col width="100">
                                </colgroup>
                                <thead>
                                <tr>
                                    <th>图片</th>
                                    <th>商品</th>
                                    <th>补贴金额（元）</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody id="selectedProducts">
                                </tbody>
                            </table>

                        </div>
                    </div>

                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit="" lay-filter="selfFormSubmit"
                                    target-form="data-form">提交
                            </button>
                            <button class="layui-btn layui-btn-warm" type="button"
                                    onclick="javascript:history.back(-1);">返回
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    // 修改监听方式为监听 document 事件
    document.addEventListener('layerClosed', function (event) {
        let data = event.detail || {};
        if (data) {
            let ids = data.ids || [];
            // 获取当前已存在的商品ID
            let existingIds = $('#selectedProducts tr.product-item').map(function () {
                return parseInt($(this).data('id'));
            }).get();
            // 过滤掉重复的商品ID
            let newIds = ids.map(Number).filter(id => !existingIds.includes(id));
            if (newIds.length === 0) {
                return;
            }

            $.post('{:url("get_goods")}', {ids: newIds}, function (res) {
                if (res.code !== -1) {
                    let html = '';
                    res.data.forEach(function (product) {
                        html += `
                        <tr class="product-item" data-id="${product.id}">
                            <td><img src="${product.image}" alt="${product.title}" style="width: 50px; height: 50px;"></td>
                            <td>
                                <p style="font-weight: bold; font-size: 18px;">${product.title}</p>
                                <p>
                                   <span>售价: ¥${product.sale_price}</span>
                                   <span>佣金: ¥${product.commission}</span>
                                </p>
                            </td>
                            <td>
                                <input class="layui-input" min="0" step="0.01" type="number" name="goods[${product.id}][price]" placeholder="补贴金额">
                            </td>
                            <td>
                                <button type="button" class="layui-btn layui-btn-danger" onclick="removeProduct(this)">删除</button>
                            </td>
                        </tr>`;
                    })
                    $('#selectedProducts').append(html);
                }
            });
        }
    });

    layui.use(['layer', 'form'], function () {
        var layer = layui.layer;
        var form = layui.form;

        // 点击添加按钮
        $('#addProductBtn').on('click', function () {
            layer.open({
                type: 2, // 页面层
                title: '添加商品',
                shadeClose: true,
                shade: 0.8,
                area: ['95vw', '100vh'],
                content: '{:url("select")}',
            });
        });

        form.on('submit(selfFormSubmit)', function (data) {
            var index = layer.load(0);
            var url = '{:url("form")}';

            $.post(url, $('.data-form').serialize()).success(function (res) {
                layer.close(index);
                layer.msg(res.msg, {time: 1000}, function () {
                    location.href = res.data.url;
                });
            });
            return false; // 阻止表单跳转
        });
    });

    // 删除商品
    function removeProduct(self) {
        $(self).closest('.product-item').remove()
    }

</script>
{/block}
